import { defineStore } from 'pinia'
import { ref } from 'vue'
import CloudBaseAPI from '@/api/cloudbase'

export const useAuthStore = defineStore('auth', () => {
  const isLoggedIn = ref(false)
  const adminInfo = ref(null)
  const token = ref('')

  // 登录
  const login = async (username, password) => {
    try {
      const result = await CloudBaseAPI.adminLogin(username, password)
      
      if (result.success) {
        isLoggedIn.value = true
        adminInfo.value = result.adminInfo
        token.value = result.token
        
        // 保存到本地存储
        localStorage.setItem('adminToken', result.token)
        localStorage.setItem('adminInfo', JSON.stringify(result.adminInfo))
        
        return { success: true }
      } else {
        return { success: false, message: result.message }
      }
    } catch (error) {
      return { success: false, message: '登录失败，请检查网络连接' }
    }
  }

  // 登出
  const logout = () => {
    isLoggedIn.value = false
    adminInfo.value = null
    token.value = ''
    
    // 清除本地存储
    localStorage.removeItem('adminToken')
    localStorage.removeItem('adminInfo')
  }

  // 检查登录状态
  const checkLoginStatus = () => {
    const savedToken = localStorage.getItem('adminToken')
    const savedAdminInfo = localStorage.getItem('adminInfo')
    
    if (savedToken && savedAdminInfo) {
      isLoggedIn.value = true
      token.value = savedToken
      adminInfo.value = JSON.parse(savedAdminInfo)
    }
  }

  return {
    isLoggedIn,
    adminInfo,
    token,
    login,
    logout,
    checkLoginStatus
  }
})